package com.xdan.memory.controller;

import com.lark.oapi.card.CardActionHandler;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.sdk.servlet.ext.ServletAdapter;
import com.lark.oapi.service.im.v1.model.EventMessage;
import com.lark.oapi.service.im.v1.model.GetChatRespBody;
import com.lark.oapi.service.im.v1.model.P2MessageReceiveV1;
import com.xdan.memory.config.RobotConfig;
import com.xdan.memory.redis.RedisUtil;
import com.xdan.memory.service.ImService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class AlarmController {

    @Resource
    private ImService im;

    @Resource
    private ServletAdapter servletAdapter;

    @Resource
    private RobotConfig robotConfig;
//
//
//    private final EventDispatcher eventDispatcher = EventDispatcher.newBuilder(robotConfig.getVerificationToken(), robotConfig.getEncryptKey())
//            .onP2MessageReceiveV1(new com.lark.oapi.service.im.v1.ImService.P2MessageReceiveV1Handler() {
//                // 处理消息回调
//                @Override
//                public void handle(P2MessageReceiveV1 event) throws Exception {
//                    EventMessage msg = event.getEvent().getMessage();
//                    if (msg.getContent().contains("/solve")) {
//                        // 发送消息
//                        im.SendMessage(msg.getChatId(), "text", "{\"text\":\"问题已解决，辛苦了!\"}");
//
//                        // 获取会话信息
//                        GetChatRespBody chatInfo = im.GetChatInfo(msg.getChatId());
//
//                        // 修改会话名称
//                        String name = chatInfo.getName();
//                        if (name.startsWith("[跟进中]")) {
////                            name = "[已解决]" + name.substring(5);
//                            name = name.substring(5);
//                        }
////                        } else if (!name.startsWith("[已解决]")) {
////                            name = "[已解决]" + name;
////                        }
//                        im.UpdateChatName(msg.getChatId(), name);
//                    }
//                }
//            })
//            .build();
//
//    private final CardActionHandler cardActionHandler = CardActionHandler.newBuilder(robotConfig.getVerificationToken(), robotConfig.getEncryptKey(),
//            cardAction -> {
//                // 处理卡片回调
//                if ("follow".equals(cardAction.getAction().getValue().get("key"))) {
//                    // 获取会话信息
//                    GetChatRespBody chatInfo = im.GetChatInfo(cardAction.getOpenChatId());
//
//                    // 修改会话名称
//                    String name = chatInfo.getName();
//                    if (!name.startsWith("[跟进中]") && !name.startsWith("[已解决]")) {
//                        name = "[跟进中] " + name;
//                    }
//                    im.UpdateChatName(cardAction.getOpenChatId(), name);
//
////                    return im.BuildCard("跟进中");
//                }
//
//                return null;
//            }).build();

    @RequestMapping("/event")
    public void event(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        EventDispatcher eventDispatcher = EventDispatcher.newBuilder(robotConfig.getVerificationToken(), robotConfig.getEncryptKey())
                .onP2MessageReceiveV1(new com.lark.oapi.service.im.v1.ImService.P2MessageReceiveV1Handler() {
                    // 处理消息回调
                    @Override
                    public void handle(P2MessageReceiveV1 event) throws Exception {
                        EventMessage msg = event.getEvent().getMessage();
                        if (msg.getContent().contains("/solve")) {
                            // 发送消息
                            im.SendMessage(msg.getChatId(), "text", "{\"text\":\"问题已解决，辛苦了!\"}");

                            // 获取会话信息
                            GetChatRespBody chatInfo = im.GetChatInfo(msg.getChatId());

                            // 修改会话名称
                            String name = chatInfo.getName();
                            if (name.startsWith("[跟进中]")) {
//                            name = "[已解决]" + name.substring(5);
                                name = name.substring(5);
                            }
//                        } else if (!name.startsWith("[已解决]")) {
//                            name = "[已解决]" + name;
//                        }
                            im.UpdateChatName(msg.getChatId(), name);
                        }
                    }
                })
                .build();
        servletAdapter.handleEvent(request, response, eventDispatcher);
    }

    //
    // 跟进处理
    @RequestMapping("/card")
    public void card(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        CardActionHandler cardActionHandler = CardActionHandler.newBuilder(robotConfig.getVerificationToken(), robotConfig.getEncryptKey(),
                cardAction -> {
                    // 处理卡片回调
                    if ("follow".equals(cardAction.getAction().getValue().get("key"))) {
                        // 获取会话信息
//                        GetChatRespBody chatInfo = im.GetChatInfo(cardAction.getOpenChatId());

                        // 修改会话名称
//                        String name = chatInfo.getName();
//                        if (!name.startsWith("[跟进中]") && !name.startsWith("[已解决]")) {
//                            name = "[跟进中] " + name;
//                        }
//                        im.UpdateChatName(cardAction.getOpenChatId(), name);

                        im.SendMessage(cardAction.getOpenChatId(), "text", "{\"text\":\"问题正在跟进中!\"}");
                        RedisUtil.setEx(cardAction.getOpenChatId(), "true", robotConfig.getNotificationInterval(), TimeUnit.MINUTES);
//                    return im.BuildCard("跟进中");
                    } else if ("solve".equals(cardAction.getAction().getValue().get("key"))) {
                        im.SendMessage(cardAction.getOpenChatId(), "text", "{\"text\":\"问题已解决，辛苦了!\"}");
                        RedisUtil.delete(cardAction.getOpenChatId());
                    } else if ("postback".equals(cardAction.getAction().getValue().get("key"))) {
                        im.SendMessage(cardAction.getOpenChatId(), "text", "{\"text\":\"已延后一天, 记得按时处理!\"}");
                        RedisUtil.setEx(cardAction.getOpenChatId(), "true", robotConfig.getDelayTime(), TimeUnit.MINUTES);
                    }

                    return null;
                }).build();
        servletAdapter.handleCardAction(request, response, cardActionHandler);
    }
}